<?php
namespace app\api\controller;
use think\Controller;
use think\Db;
use ChuanglanSmsApi;
class Send_wxmessage extends Common
{
	 /*********微信模板消息开始************/
     /*
     *
     *$uid   用户ID
     *$template_id  模板ID
     *$message    消息通知内容
     *$path   查看跳转小程序的地址
     *
     *
     */
    public function tosendlj($uid,$template_id,$message,$path,$type=1){
        // echo 111111;die;
        // return 1;die;
        $openid = Db::name('store')->where('id',$uid)->value('open_id');
        
        if(!empty($openid)){
            $data=[
                'touser'=>$openid,
                'template_id'=>$template_id,
                'url'=>'',
                "miniprogram"=>[
                    
                ],
                'topcolor'=>"#FF0000",
                'data'=>$message
            ];    
            // dump($data);die;
            // write_log($data);
            $tes = $this->sendtempletsmsg($data,$type);
            return $tes;
        }else{
            return false;
        }
      
    }

    public function https_request($url,$data = null){
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
        if (!empty($data)){
            curl_setopt($curl, CURLOPT_POST, 1);
            curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
        }
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($curl, CURLOPT_NOSIGNAL,true);//支持毫秒级别超时设置
        curl_setopt($curl, CURLOPT_TIMEOUT_MS, 1000);
        $output = curl_exec($curl);
        curl_close($curl);
        return $output;
    }

    public function get_all_access_token(){
        
        $access_token_jilu = Db::name('weixin_config')->where('id',1)->find();
        
        if(time()-intval($access_token_jilu['oaexp_time'])>3600 || $access_token_jilu['oaaccess_token']==''){
            $appid = $access_token_jilu['oaappid'];
            $secret =  $access_token_jilu['oaappsecret'];
            $url = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid='.$appid.'&secret='.$secret;
            $res = $this->http_curl($url);
            // var_dump($res);die;
            $access_token = $res['access_token'];
            $update_data = [
                'oaexp_time' =>time(),
                'oaaccess_token'=>$access_token
            ];
            
            $update_data = Db::name('weixin_config')->where('id',1)->update($update_data);
            
        }else{
            $access_token = $access_token_jilu['oaaccess_token'];
            
        }
        // dump($access_token);die;
        return $access_token;

    }
  
    
    //链接qipei数据库的参数
    public function xmyc_db(){
        $db2 = [
            'type'     => 'mysql',
            'hostname' => 'localhost',
            'database' => 'qipei',
            'username' => 'qipei',
            'password' => 'zLSTZXFTSrMdJsEs'
        ];
        return $db2;
    }
    //查询微信配置信息
    public function xmyc_token(){
        // 连接第二个数据库
        $db2 = \think\Db::connect($this->xmyc_db());
        // 执行查询操作
        $result = $db2->name('car_weixin_config')->where('id', 1)->find();
        write_log('查询token啊','wxsendlog');
        write_log('测试版','wxsendlog');
        return $result;
    }
    //更新微信配置信息
    public function xmyc_token_up($data){
        // 连接第二个数据库
        $db2 = \think\Db::connect($this->xmyc_db());
        // 执行查询操作
        $result = $db2->name('car_weixin_config')->where('id', 1)->update($data);
        write_log('修改token啊','wxsendlog');
        write_log('测试版','wxsendlog');
        return $result;
    }
    public function http_curl($url,$type='get',$res='json',$arr=''){
        /*
        $url 请求的url
        $type 请求类型
        $res 返回数据类型
        $arr post请求参数
         */
        $ch=curl_init();
        /*$url='https://api.weixin.qq.com/cgi-bin/token?

        grant_type=client_credential&appid=wxf71d53c65df41aab&secret=e31e44c35067fb75759f53eed1cb1b26';  */
        curl_setopt($ch,CURLOPT_URL,$url);
        curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        if($type=='post'){
            curl_setopt($ch,CURLOPT_POST,1);
            curl_setopt($ch,CURLOPT_POSTFIELDS,$arr);
        }
        $output = curl_exec($ch);
        curl_close($ch);
        if($res=='json'){
            return json_decode($output,true);
        }
    }

    public function sendtempletsmsg($data,$type){
        
        $get_all_access_token = $this->get_all_access_token();
       
        
        write_log('公众号通知--'.date('Y-m-d H:i:s').'--'.$data['template_id'],'wxsend');
        write_log($data,'wxsend');
        $json_data=json_encode($data);//转化成json数组让微信可以接收

        $url="https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=".$get_all_access_token;//模板消息请求URL
        // write_log($data);
        $res=$this->https_request($url,urldecode($json_data));//请求开始
        write_log($res,'wxsend');
        $res=json_decode($res,true);
        // dump($res);die;
        write_log($res,'wxsend');
        if($res['errcode']==0 && $res['errcode']=="ok"){            
            return ['code'=>1];
        }else{
            return ['code'=>-4];
        }

    }
    /*********微信模板消息结束************/
    /*********微信订阅消息开始************/
     /*
     *
     *$uid   用户ID
     *$template_id  模板ID
     *$message    消息通知内容
     *$path   查看跳转小程序的地址
     *$type   类型1用户2门店
     *
     */
    public function wxsendlj($uid,$template_id,$message,$path,$type=1){
        if($type==1){
            $openid = Db::name('user')->where('user_id',$uid)->value('open_id');
        }elseif ($type==3) {
            $openid = Db::name('user')->where('user_id',$uid)->value('kd_open_id');
        }else{
            $openid = Db::name('store_user')->where('user_id',$uid)->value('open_id');
        }
        
        if(!empty($openid)){
            $data=[
                'touser'=>$openid,
                'template_id'=>$template_id,
                'page'=>$path,
                'data'=>$message
            ];    
            // dump($data);die;
            // write_log($data);
            $tes = $this->subscribeMessage($data,$type);
            return $tes;
        }else{
            return false;
        }
      
    }
    public function subscribeMessage($data,$type){
        if($type==3){
            $get_all_access_token = $this->get_all_access_tokenss();
        }elseif($type==2){
            $get_all_access_token = $this->get_all_access_tokensstore();
        }else{
            $get_all_access_token = $this->get_all_access_wxtoken();
        }
        
        // write_log('小程序通知--'.date('Y-m-d H:i:s').'--'.$data['template_id']);
        $json_data=json_encode($data);//转化成json数组让微信可以接收

        $url="https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=".$get_all_access_token;//模板消息请求URL
        
        $res=$this->https_request($url,urldecode($json_data));//请求开始

        $res=json_decode($res,true);
        // dump($res);die;
        // write_log($res);
        if($res['errcode']==0){            
            return ['code'=>1];
        }else{
            return ['code'=>-4];
        }

    }
    /*获取令牌*/
    public function get_all_access_wxtoken(){
        
        
        $info = Db::name('weixin_config')->where('id','1')->find();
        $appid = $info['appid'];
        $appsecret = $info['appsecret'];
        $last_time = $info['last_time'];
        $express = $info['express'];
        $access_token = $info['access_token'];
        if(!$access_token || time()-intval($last_time)>$express){
           
            $url = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid='.$appid.'&secret='.$appsecret;
            $res = self::http_curl($url);
            $access_token = $res['access_token'];
            $update_data = [
             'access_token'=>$access_token,
                'last_time'=>time()
            ];
            $update_data = Db::name('weixin_config')->where('id','1')->update($update_data);
        }
        return $access_token;

    }
     /*获取令牌洗美养车*/
    public function get_all_access_tokenss(){
        $info = db('weixin_config')->where('id','1')->find();
        $appid = $info['kd_appid'];
        $appsecret = $info['kd_appsecret'];
        $express = $info['kd_express'];
        $access_token = $info['kd_access_token'];
        if(!$access_token || time()>$express){
           
            $url = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid='.$appid.'&secret='.$appsecret;
            $res = self::http_curl($url);
            $access_token = $res['access_token'];
            $update_data = [
                'kd_access_token'=>$access_token,
                'kd_express'=>time()+7000
            ];
            $update_data = db('weixin_config')->where('id','1')->update($update_data);
        }
        return $access_token;

    }
    /*获取令牌智慧店长*/
    public function get_all_access_tokensstore(){
        $info = db('weixin_config')->where('id','1')->find();
        $appid = $info['appids'];
        $appsecret = $info['appsecrets'];
        $express = $info['expresss'];
        $access_token = $info['access_tokens'];
        if(!$access_token || time()>$express){
            
            $url = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid='.$appid.'&secret='.$appsecret;
            $res = self::http_curl($url);
            $access_token = $res['access_token'];
            $update_data = [
                'access_tokens'=>$access_token,
                'expresss'=>time()+7000
            ];
            $update_data = db('weixin_config')->where('id','1')->update($update_data);
        }
        return $access_token;

    }
    /*********微信订阅消息结束************/
}